// stores/finance.js
import { defineStore } from 'pinia'
import api from '@/api'

export const useFinanceStore = defineStore('finance', {
  state: () => ({
    vouchers: [],
    accountingSubjects: [],
    loading: false,
    currentVoucher: null,
    newVoucher: {
      entries: []
    },
    filters: {
      period: '',
      status: ''
    }
  }),

  getters: {
    // 获取已过账凭证
    postedVouchers: (state) => {
      return state.vouchers.filter(v => v.status === 'POSTED')
    },

    // 计算借贷平衡
    isBalanced: (state) => {
      if (!state.currentVoucher?.entries) {
        // 检查新建凭证的平衡性
        if (!state.newVoucher?.entries) return true
        const totalDebit = state.newVoucher.entries.reduce((sum, entry) => sum + (entry.debit_amount || 0), 0)
        const totalCredit = state.newVoucher.entries.reduce((sum, entry) => sum + (entry.credit_amount || 0), 0)
        return Math.abs(totalDebit - totalCredit) < 0.01
      }
      const totalDebit = state.currentVoucher.entries.reduce((sum, entry) => sum + (entry.debit_amount || 0), 0)
      const totalCredit = state.currentVoucher.entries.reduce((sum, entry) => sum + (entry.credit_amount || 0), 0)
      return Math.abs(totalDebit - totalCredit) < 0.01
    }
  },

  actions: {
    // 获取凭证列表
    async fetchVouchers(filters = {}) {
      this.loading = true
      try {
        const params = { ...this.filters, ...filters }
        const response = await api.get('/finance/vouchers', { params })
        this.vouchers = response.data
        return response.data
      } catch (error) {
        console.error('获取凭证失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取会计科目列表
    async fetchAccountingSubjects() {
      this.loading = true
      try {
        const response = await api.get('/finance/subjects')
        this.accountingSubjects = response.data
        return response
      } catch (error) {
        console.error('获取会计科目失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 创建新凭证
    async createVoucher(voucherData) {
      try {
        const response = await api.post('/finance/vouchers', voucherData)
        // 添加到凭证列表
        this.vouchers.unshift(response.data)
        return response.data
      } catch (error) {
        console.error('创建凭证失败:', error)
        throw error
      }
    },

    // 获取凭证详情
    async fetchVoucherDetail(voucherId) {
      try {
        const response = await api.get(`/finance/vouchers/${voucherId}`)
        this.currentVoucher = response.data
        return response.data
      } catch (error) {
        console.error('获取凭证详情失败:', error)
        throw error
      }
    },

    // 过账凭证
    async postVoucher(voucherId) {
      try {
        const response = await api.put(`/finance/vouchers/${voucherId}/post`)
        // 更新凭证列表中的状态
        const voucherIndex = this.vouchers.findIndex(v => v.id === voucherId)
        if (voucherIndex !== -1) {
          this.vouchers[voucherIndex] = response.data
        }
        // 如果当前查看的是这个凭证，也更新当前凭证
        if (this.currentVoucher && this.currentVoucher.id === voucherId) {
          this.currentVoucher = response.data
        }
        return response.data
      } catch (error) {
        console.error('过账凭证失败:', error)
        throw error
      }
    }
  }
})